package com.soikc.kuaidiE.mvc;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 映射器(包含了大量的网站与方法的关系)
 */
public class HandLerMapping {
    private static Map<String, MVCMapping> data = new HashMap<>();

    public static MVCMapping get(String url){
        return data.get(url);
    }
    public static void load(InputStream is) throws IOException {
        String s = IOUtils.toString(is, StandardCharsets.UTF_8);

        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray aClass = jsonObject.getJSONArray("class");
        for (Object o : aClass) {
            String o1 = (String) o;
            try {
                //加载配置文件描述的类
                Class c = Class.forName(o1);
                //创建对象
                Object obj = c.getConstructor().newInstance();
                Method[] methods = c.getMethods();
                for (Method m : methods) {
                    Annotation[] as = m.getAnnotations();
                    if (as == null) {
                        continue;
                    }
                    for (Annotation annotation : as) {
                        if (annotation instanceof ResponseBody) {
                            MVCMapping mvcMapping = new MVCMapping(obj, m, ResponseType.TEXT);
                            data.put(((ResponseBody) annotation).value(), mvcMapping);
                        } else if (annotation instanceof ResponseView) {
                            MVCMapping mvcMapping = new MVCMapping(obj, m, ResponseType.VIEW);
                            data.put(((ResponseView) annotation).value(), mvcMapping);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class MVCMapping {
        private Object obj;
        private Method method;
        private ResponseType type;

        public MVCMapping() {
        }

        public MVCMapping(Object obj, Method method, ResponseType type) {
            this.obj = obj;
            this.method = method;
            this.type = type;
        }

        public Object getObj() {
            return obj;
        }

        public void setObj(Object obj) {
            this.obj = obj;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }

        public ResponseType getType() {
            return type;
        }

        public void setType(ResponseType type) {
            this.type = type;
        }
    }
}